<?php
include 'dbconnect.php';

if ($_REQUEST['submit'] == "Upload") {
    $allowedExts = array("gif", "jpeg", "jpg", "png", "svg");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);

    if (in_array($extension, $allowedExts)) {
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        } else {
            if (file_exists("upload/" . $_FILES["file"]["name"])) {
                echo $_FILES["file"]["name"] . " already exists.";
            } else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
            }
        }
    } else {
        echo "Invalid image file.";
    }

    $imageName = $_FILES["file"]["name"];
    $path = "upload/" . $imageName;

    $sql = "INSERT INTO Images (ProductID, ImageName, Path) VALUES (?, ?, ?)";

    $query = $db->prepare($sql);

    $query->bindValue(1, $productID);
    $query->bindValue(2, $imageName);
    $query->bindValue(3, $path);

    try {
        $query->execute();
    } catch (PDOException $error) {
        echo $error->getMessage();
    }
}
?>